<template>
  <div :id="id" class="line-numbers"/>
</template>

<script>
import '@toast-ui/editor/dist/toastui-editor.css' // Editor's Style
import '@toast-ui/editor-plugin-code-syntax-highlight/dist/toastui-editor-plugin-code-syntax-highlight.css'

import Prism from 'prismjs'

import Viewer from '@toast-ui/editor/dist/toastui-editor-viewer'
import codeSyntaxHighlight
  from '@toast-ui/editor-plugin-code-syntax-highlight/dist/toastui-editor-plugin-code-syntax-highlight-all.js'

import '@toast-ui/editor/dist/i18n/zh-cn'

export default {
  name: 'MarkdownViewer',
  props: {
    value: {
      type: String,
      default: ''
    },
    id: {
      type: String,
      required: false,
      default() {
        return 'markdown-editor-' + +new Date() + ((Math.random() * 1000).toFixed(0) + '')
      }
    },
    mode: {
      type: String,
      default: 'markdown'
    },
    height: {
      type: String,
      required: false,
      default: '300px'
    },
    language: {
      type: String,
      required: false,
      default: 'zh-CN' // https://github.com/nhnent/tui.editor/tree/master/src/js/langs
    }
  },
  data() {
    return {
      viewer: null
    }
  },
  computed: {
    editorOptions() {
      const options = Object.assign({}, this.options)
      options.initialEditType = this.mode
      options.height = this.height
      options.language = this.language
      options.plugins = [[codeSyntaxHighlight, { highlighter: Prism }]]
      return options
    }
  },
  watch: {
    value(newValue, preValue) {
      console.log(preValue)
      if (newValue !== preValue) {
        this.viewer.setMarkdown(newValue)
        this.$nextTick(() => {
          Prism.highlightAll()
        })
      }
    },
    language(val) {
      this.destroyViewer()
      this.initViewer()
    },
    height(newValue) {
      this.viewer.height(newValue)
    },
    mode(newValue) {
      this.viewer.changeMode(newValue)
    }
  },
  mounted() {
    this.initViewer()
  },
  destroyed() {
    this.destroyViewer()
  },
  methods: {
    initViewer() {
      this.viewer = new Viewer({
        el: document.getElementById(this.id),
        ...this.viewerOptions
      })
      if (this.value) {
        this.viewer.setMarkdown(this.value)
      }
    },
    destroyViewer() {
      if (!this.viewer) return
      this.viewer.off('change')
    },
    setValue(value) {
      this.viewer.setMarkdown(value)
    },
    setHtml(value) {
      this.viewer.setHtml(value)
    },
    getHtml() {
      return this.viewer.preview
    }
  }
}
</script>

<style>

.toastui-editor-contents {
  font-family: Helvetica Neue, Helvetica, PingFang SC, Hiragino Sans GB, Microsoft YaHei, Arial, sans-serif;
}

</style>
